package com.huiminpay.merchant.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.huiminpay.common.cache.domain.BusinessException;
import com.huiminpay.common.cache.domain.CommonErrorCode;
import com.huiminpay.common.cache.util.RandomUuidUtil;
import com.huiminpay.merchant.api.MerchantService;
import com.huiminpay.merchant.common.util.SecurityUtil;
import com.huiminpay.merchant.convert.MerchantDetailConvert;
import com.huiminpay.merchant.convert.MerchantRegisterConvert;
import com.huiminpay.merchant.dto.MerchantDTO;
import com.huiminpay.merchant.service.SmsService;
import com.huiminpay.merchant.vo.MerchantDetailVO;
import com.huiminpay.merchant.vo.MerchantRegisterVo;
import io.swagger.annotations.*;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @ClassName: MerchantController
 * @Package: com.huiminpay.merchant.controller
 * @Description: 控制层
 * @Author 谢同学
 * @Create 2023/11/15 17:00
 * @Version 1.0
 */

@RestController
@Api(value = "商户", tags = "商户平台", description = "商户平台应用")
public class MerchantController {
    @Reference  //dubbo 服务发现
     MerchantService merchantService;

    @Autowired
    private SmsService smsService;

    /**
     * 获取验证码
     *
     * @param phone 客户手机号
     * @return
     */
    @ApiOperation(value = "获取验证码")
    @ApiImplicitParam(name = "phone", value = "客户手机号", paramType = "query", dataType = "String")
    @GetMapping("sms")
    public String getSesCode(@RequestParam String phone) {
        return smsService.sendSms(phone);
    }

    /**
     * 商户注册
     *
     * @param merchantRegister 注册信息
     * @return
     */
    @ApiOperation("注册商户")
    @ApiImplicitParam(name = "merchantRegister", value = "注册信息", dataType =
            "MerchantRegisterVo", paramType = "body")
    @PostMapping("/merchants/register")
    public MerchantRegisterVo registerMerchant(@RequestBody MerchantRegisterVo merchantRegister) {
        //校验验证码
        smsService.checkVerifiyCode(merchantRegister.getVerifiykey(),
                merchantRegister.getVerifiyCode());
        //注册商户
        //vo转DTO
        MerchantDTO merchantDTO = MerchantRegisterConvert.INSTANCE.vo2dto(merchantRegister);
//        MerchantDTO merchantDTO = new MerchantDTO();
//        merchantDTO.setUsername(merchantRegister.getUsername());
//        merchantDTO.setMobile(merchantRegister.getMobile());
        //调用商户服务添加商户方法
        merchantService.createMerchant(merchantDTO);
        return merchantRegister;
    }


    @Autowired
    private OSS oss;

    @Value("${oss.aliyun.domain}")
    private String domain;
    @Value("${oss.aliyun.bucket}") //
    private String bucket;


    /**
     * 文件上传
     *
     * @param file MultipartFile是Spring框架提供的接口，用于处理文件上传
     * @return 文件地址
     */
    @ApiOperation("文件上传")
    @ApiImplicitParam(name = "file", value = "上传的文件", paramType = "body", dataType = "MultipartFile")

    @PostMapping("upload")
    public String upload(@ApiParam(value = "证件照", required = true)
                         @RequestParam("file") MultipartFile file) {
        if (file != null) {

            //获取文件名
            String originalFilename = file.getOriginalFilename();
            //获取文件拓展名
            String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
            //文件名+拓展名（uuid加密）
//            String filename ="merchant/images/"+RandomUuidUtil.getUUID() + substring;
            String filename = RandomUuidUtil.getUUID() + substring;

            try {
                //创建上传文件对象，OssAC.BUCKET：指定文件存储地址
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filename, file.getInputStream());
                //上传文件
                oss.putObject(putObjectRequest);
                //返回全路径
                return domain + filename;
            } catch (IOException e) {
                throw new BusinessException(CommonErrorCode.E_100106);//文件上传错误
            }
        } else {
            throw new BusinessException(CommonErrorCode.E_100108);//参数为空
        }
    }

    /**
     * 资质申请
     * @param merchantInfo 商户认证资料
     */
    @ApiOperation("资质申请")
    @PostMapping("/my/merchants/save")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "merchantInfo", value = "商户认证资料", required = true, dataType = "MerchantDetailVO", paramType = "body")
    })
    public void saveMerchant(@RequestBody MerchantDetailVO merchantInfo){
        //vo转dto
        MerchantDTO merchantDTO = MerchantDetailConvert.INSTANCE.vo2dto(merchantInfo);
        //解析token，取出当前登录商户的id
        Long merchantId = SecurityUtil.getMerchantId();
//        long merchantId = 1725123942044528641L;

        merchantService.applyMerchant(merchantId,merchantDTO);
    }

    @ApiOperation("根据id查询商户信息")
    @ApiImplicitParam(name = "id", value = "商户id", required = true, dataType = "Long", paramType = "path")
    @GetMapping("/merchants/{id}")
    public MerchantDTO queryMerchantById(@PathVariable("id") Long id) {
        MerchantDTO merchantDTO = merchantService.queryMerchantById(id);
        return merchantDTO;
    }

    @ApiOperation("获取登录用户的商户信息")
    @GetMapping(value = "/my/merchants")
    public MerchantDTO getMyMerchantInfo() {
        // 从token 中获取商户id
        Long merchantId = SecurityUtil.getMerchantId();
        MerchantDTO merchant = merchantService.queryMerchantById(merchantId);
        return merchant;
    }
}
